package hhtc.jsjds.auth;

import hhtc.jsjds.filter.JwtTokenAuthenticationFilter;
import hhtc.jsjds.security.JwtAuthenticationConfig;
import hhtc.jsjds.securityhandler.GoAccessDeniedHandler;
import hhtc.jsjds.securityhandler.GoAuthenticationEntryPoint;
import hhtc.jsjds.securityhandler.GoLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationConfig config;


    @Bean
    public JwtAuthenticationConfig jwtConfig() {
        return new JwtAuthenticationConfig();
    }

    @Bean
    public JwtTokenAuthenticationFilter goJwtTokenAuthenticationFilter(){
        return new JwtTokenAuthenticationFilter(this.config);
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity
                .csrf().disable()
                .logout().disable()
                .formLogin().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()

                .anonymous()
                .and()
                .exceptionHandling()// 未经过认证的用户访问受保护的资源
                .authenticationEntryPoint(new GoAuthenticationEntryPoint())
                .and()
                .exceptionHandling()
                // 已经认证的用户访问自己没有权限的资源处理
                .accessDeniedHandler(new GoAccessDeniedHandler())
                .and()
                .logout()
                .logoutSuccessHandler(new GoLogoutSuccessHandler())
                .and()
                .addFilterBefore(goJwtTokenAuthenticationFilter(),
                        UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers(config.getUrl()).permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/review-service/review/**","/user-service/competition/eliminate").hasAnyRole("REVIEWRATER","SYSADMIN")
                .antMatchers("/user-service/student/**","/user-service/competition/**").hasAnyRole("STUDENT","SYSADMIN")
                .antMatchers("/review-service/final/**").hasAnyRole("FINALRATER")
                .antMatchers("/review-service/sysadmin/**").hasAnyRole("SYSADMIN")
                .antMatchers("/auth-center/**","/images/**", "/login", "/auth/**","/access/**","/common/**").permitAll();
    }
}

